package com.atwork.wuhua.base;

import android.accounts.NetworkErrorException;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by Administrator on 2018/3/13 0013.
 */

public abstract class BaseObserver<T> implements Observer<BaseEntity<T>> {
    private String TAG = "ssss";
    protected Context mContext;

    public BaseObserver(Context cxt) {
        this.mContext = cxt;
    }

    public BaseObserver() {
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {

        onRequestStart(d);
    }


    @Override
    public void onNext(BaseEntity<T> tBaseEntity) {
        onRequestEnd();
        try {
            onSuccees(tBaseEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onError(Throwable e) {
        Log.e(TAG, "失败原因:==>" + e.toString() + ""); //这里可以打印错误信息
        onRequestEnd();
        try {
            if (e instanceof ConnectException || e instanceof TimeoutException) {
                Toast.makeText(MyApplication.getMyApplication(), "网络连接超时", Toast.LENGTH_SHORT).show();
                onFailure(e, true);
            } else if (e instanceof NetworkErrorException) {
                Toast.makeText(MyApplication.getMyApplication(), "没有网络连接", Toast.LENGTH_SHORT).show();
                onFailure(e, true);
            } else if (e instanceof UnknownHostException) {
                Toast.makeText(MyApplication.getMyApplication(), "没有网络连接", Toast.LENGTH_SHORT).show();
                onFailure(e, true);
            } else {
                Toast.makeText(MyApplication.getMyApplication(), e.toString(), Toast.LENGTH_SHORT).show();
                onFailure(e, false);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onComplete() {
    }

    /**
     * 返回成功
     *
     * @param t
     * @throws Exception
     */
    protected abstract void onSuccees(BaseEntity<T> t) throws Exception;

    /**
     * 返回成功了,但是code错误
     *
     * @param t
     * @throws Exception
     */
    protected void onCodeError(BaseEntity<T> t) throws Exception {
    }

    /**
     * 返回失败
     *
     * @param e
     * @param isNetWorkError 是否是网络错误
     * @throws Exception
     */
    protected abstract void onFailure(Throwable e, boolean isNetWorkError) throws Exception;

    protected abstract void onRequestStart(Disposable disposable);

    protected void onRequestEnd() {
        closeProgressDialog();
    }

    public void showProgressDialog() {
//        ProgressDialog.show(mContext, false, "请稍后");
    }

    public void closeProgressDialog() {
//        ProgressDialog.cancle();
    }
}
